// miniprogram/pages/admin/schedule/newSchedule/newSchedule.js
const app = getApp();
const util = require("../../../utils/util");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    today: util.formatTime(new Date()).substr(0,10)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.login(user=>{
      if (!user.studioid) {
        wx.navigateBack();
        return;
      }
      this.loadItem(options);
    })

  },

  loadItem: function(options){
    wx.showNavigationBarLoading();
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'get',
        table: 'order',
        // field: {customer: true, price: true, service: true, remark: true},
        where: {_id: options._id, studioid: app.globalData.user.studioid}
      },
      success: res=>{
        wx.hideNavigationBarLoading();
        if (res.result.data.length == 0){
          wx.showModal({
            content: '订单不存在',
            showCancel: false,
            success: rr=>{
              wx.navigateBack();
            }
          })
        }else{
          this.setData({order: res.result.data[0]});
       
        }
      }
    });
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'get',
        table: 'team',
        field: {name: true},
        where: {studioid: app.globalData.user.studioid}
      },
      success: res=>{
        wx.hideNavigationBarLoading();
        // let team = {};
        // res.result.data.map((v,i)=>{
        //   team[v._id] = v.name;
        // })
        this.setData({team: res.result.data});
      }
    });
    this.setData({agenda: {studioid: app.globalData.user.studioid, orderid: this.options._id}})
    // if (options._id){
      wx.showLoading({
        title: '正在加载数据',
      });
      wx.cloud.callFunction({
        name: 'crud',
        data: {
          op: 'get',
          table: 'agenda',
          where: {orderid: this.options._id, studioid: app.globalData.user.studioid}
        },
        success: res=>{
          wx.hideLoading();
          if (res.result.data.length > 0){
            this.setData({agenda: res.result.data[0]});
            // wx.setNavigationBarTitle({
            //   title: '重设档期'
            // })
          }
        }
      });
    // }
  },

  switchChange: function(e){
    if (e.target.id){
      this.setData({[`agenda.${e.target.id}`]: e.detail.value});
    }else{
      console.error("控件没有设置 id!")
    }
  },

  selectTeam: function(e){
    const team = this.data.team;
    // let agenda = this.data.agenda;
    this.setData({'agenda.team': team[e.detail.value]});
  },

  chooseDate: function(e){
    const that = this;
    // 弹出窗口选择日期
    wx.navigateTo({
      url: '/pages/admin/schedule/chooseDate/chooseDate',
      events: {
        selectDate: res => {
          console.log("result", res);
          that.setData({'agenda.date': res});
        }
      },
      success: res => {
        res.eventChannel.emit('setDate', {
          date: that.data.agenda.date||false
        })
      }
    })
  }, 

  submitData(agenda){
    const that = this;
    wx.cloud.callFunction({
      name: 'agenda',  // TODO 添加专用云函数，以判断排期冲突
      data: {
        op: 'update',
        // table: 'agenda',
        agenda: agenda
      },
      success: res=>{
        if (res.result.success){
          let pages = getCurrentPages();
          if (pages.length > 1){
            pages[pages.length-2].onLoad(pages[pages.length-2].options);
          }
        wx.navigateBack();
        }else{
          wx.showModal({
            content: res.result.errMsg,
            showCancel: false
          });
          // ({
          //   title: res.result.errMsg,
          //   icon: 'none',
          //   duration: 3000,
          //   success: rr=>{
          //     // wx.navigateBack(); 
          //   }
          // })
        }
        // const order = that.data.order;
        // if (!order.logs){
        //   order.logs = [];
        // }
        // order.logs.push({
        //   time: util.formatTime(new Date()),
        //   user: app.globalData.user.nickName,
        //   text: `排期拍摄`
        // })
        // wx.cloud.callFunction({
        //   name: 'crud',
        //   data: {
        //     op: 'update',
        //     table: 'order',
        //     data: {_id: agenda.orderid, status: 2, logs: order.logs}
        //   },
        //   success: rr=>{
        //     let pages = getCurrentPages();
        //     if (res.result._id || res.result.stats.updated){
        //       if (pages.length > 1){
        //         pages[pages.length-2].onLoad(pages[pages.length-2].options);
        //       }
        //       wx.navigateBack();
        //     }
        //   }
        // })
      }
    })
  },

  apply: function(e){
    console.log(e.detail.value)
    let agenda = this.data.agenda;
    for(var n in e.detail.value){
      agenda[n] = e.detail.value[n]
    }
    console.log(agenda)
    agenda.phone = this.data.order.customer.phone;
    agenda.service = this.data.order.service.title;
    //agenda.remark = this.data.order.remark;
    agenda.user = app.globalData.user.name;
    agenda.status = 0;
    this.submitData(agenda);
  },
  requestSubscribeMessage(e) {
    app.requestOrderSubscribeMessage()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.loadItem(this.options);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})